# -*- coding: utf-8 -*-
import logging
import datetime
import time
import csv

import pytz
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.wrapper import BarData

class IBNewsApp(EClient, EWrapper):
    def __init__(self):
        EWrapper.__init__(self)
        EClient.__init__(self, wrapper=self)

    def nextValidId(self, orderId:int):
        print("Next Valid Id:", orderId)
        self.start()

    def historicalNews(self, requestId:int, time:str, providerCode:str, articleId:str, headline:str):
        print("Historical News:", requestId, time, providerCode, articleId, headline)
        self.reqNewsArticle(requestId, providerCode= providerCode, articleId=articleId, newsArticleOptions=[])

    def historicalNewsEnd(self, requestId:int, hasMore:bool):
        print("Historical News End:", requestId, hasMore)

    def historicalData(self, reqId: int, bar: BarData):
        print("DATA", reqId, bar)
        with open(f"./data/stock_{reqId}.csv", "a") as csvfile:
            writer = csv.writer(csvfile)

            writer.writerow(["date", bar.date, "open", bar.open, "hign", bar.high, "close", bar.close, "volume", bar.volume, "wap", bar.wap, "count", bar.barCount])
    def start(self):
        self.getHistoricalDates()

    def getHistoricalDates(self):
        mycontract = Contract()
        # mycontract.conId = 265598
        mycontract.symbol = "NVDA"
        mycontract.secType = "STK"
        mycontract.currency = "USD"
        mycontract.exchange = "SMART"
        mycontract.primaryExchange = "NASDAQ"

        d = datetime.datetime.now()
        d2 = datetime.timedelta(hours=-96)
        # eastern_tz = pytz.timezone('US/Eastern')
        endtime = (d + d2).strftime("%Y%m%d %H:%M:%S")
        # 这里需要换成本地时区信息
        endtime_str = endtime + " Asia/Shanghai"
        print(endtime_str)
        self.reqHistoricalData(
            reqId=124,
            contract=mycontract,
            endDateTime=endtime_str,
            durationStr="2 W",
            barSizeSetting="15 mins",  # "15 mins"
            whatToShow="TRADES",
            useRTH=0,
            formatDate=1,
            keepUpToDate=False,
            chartOptions=[],
        )


if __name__ == "__main__":
    app = IBNewsApp()
    app.connect("127.0.0.1", 7496, 0)
    app.run()
